package com.mgq.netty.chat.service;

import com.mgq.netty.chat.config.ConfigProperties;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ServiceFactory {
    private static ConcurrentHashMap<Class<?>, Object> service = new ConcurrentHashMap<>();

    static Properties properties;

    static {
        try (InputStream in = ConfigProperties.class.getResourceAsStream("/application.properties")) {

            properties = new Properties();
            properties.load(in);
            Set<String> sets = properties.stringPropertyNames();
            for (String name : sets) {
                if (name.endsWith("Service")) {
                    Class<?> interfaceClass = Class.forName(name);
                    Class<?> objectClass = Class.forName(properties.getProperty(name));
                    service.put(interfaceClass, objectClass.newInstance());
                }
            }
        } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static <T> T getService(Class<T> name) {
        return (T) service.get(name);
    }
}
